package org.tgcloud.group.service.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.tgcloud.group.core.DateUtil;
import org.tgcloud.group.core.RedisUtil;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.entity.MjBusinessAccount;
import org.tgcloud.group.entity.MjBusinessAccountFollow;
import org.tgcloud.group.entity.MjOrder;
import org.tgcloud.group.entity.MjProject;
import org.tgcloud.group.repository.*;
import org.tgcloud.group.service.manager.BusinessAccountManageService;
import org.tgcloud.group.web.controller.dto.order.BusinessProjectDTO;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhy
 * @create: 2024-01-11 13:18
 * @description: 商务客户相关的定时任务
 */
@Slf4j
@Component
public class BusinessAccountTask {

    @Autowired
    private SysLabelValueMapper sysLabelValueMapper;

    @Autowired
    private MjBusinessAccountMapper businessAccountMapper;

    @Autowired
    private MjBusinessAccountFollowMapper businessAccountFollowMapper;

    @Autowired
    private MjProjectMapper projectMapper;

    @Autowired
    private MjOrderMapper orderMapper;
    @Autowired
    private BusinessAccountManageService businessAccountManageService;

    @Scheduled(cron = "0 30 0 * * ?")
    public void doUpdateBusinessAccount2() {
        if (RedisUtil.existKey("doUpdateBusinessAccount2")){
            return;
        }
        RedisUtil.setCacheObject("doUpdateBusinessAccount2", "doUpdateBusinessAccount2", 60L, TimeUnit.SECONDS);
        //        关于客保：
        //        1.提交表单受保3个月，三个月内必须每两周跟进一次，否则掉保(15天)
        //        2.成交客户保护机制：
        //①确认签单后必须每月跟进一次，否则掉保；跟进保护直到项目执行完；
        //②项目执行完之后每个月跟进一次，可以续保半年。半年之后没有新的表单则会掉保。
        //③有新的表单之后按新客户保护（如果①条的保护时间长按①的来；）
        List<MjBusinessAccount> mjBusinessAccounts = businessAccountMapper.selectTaskList();
        for (MjBusinessAccount businessAccount : mjBusinessAccounts){
            MjOrder chooseOrder = orderMapper.selectMsgByBrandId(businessAccount.getId());
            Integer orderType = 1;
            if (chooseOrder != null && chooseOrder.getFileType() != null && (chooseOrder.getFileType() == 2 || chooseOrder.getFileType() == 3)){
                orderType = 2;
            }
            if (businessAccount.getStatus() == 3){
                // 根据订单查询出对应的订单类型，1、核价订单，2、本地生活、酒店民宿
                // 提交表单受保处理
                if (businessAccount.getOrderTime() == null){
                    // 如果没有订单开始时间
                    MjOrder order = orderMapper.selectMsgByBrandId(businessAccount.getId());
                    businessAccount.setOrderTime(order.getCreateTime());
                }
                Date endTime = null;
                String sysValue = sysLabelValueMapper.selectValueBySysIdAndReadOne(33);
                if (orderType == 2){
                    sysValue = sysLabelValueMapper.selectValueBySysIdAndReadOne(52);
                }

                endTime = DateUtil.getChooseDate(businessAccount.getOrderTime(), 2, Integer.valueOf(sysValue));
                if (businessAccount.getEndTime() != null && endTime.after(businessAccount.getEndTime())){
                    endTime = businessAccount.getEndTime();
                }
                if (endTime.before(new Date())){
                    // 提交表单受保整个时段内没有进行签单，状态变更为已掉保
                    businessAccount.setStatus((short) 8);
                }else {
                    // 在签单的受保护月份内，处理逻辑在新增跟进记录里
                }
                businessAccountMapper.updateByPrimaryKeySelective(businessAccount);
            }else if (businessAccount.getStatus() == 4){
                if (orderType == 2){
                    // 对本地生活和酒店民宿进行特殊处理
                    // 判断确认签单与执行完成后的逻辑
                    BusinessProjectDTO project = businessAccountManageService.getMatchOrderLocalByBusinessAccountId(businessAccount.getId(), null);
                    if (project == null){
                        businessAccount.setStatus((short) 8);
                    }else {
                        String sysValue = sysLabelValueMapper.selectValueBySysIdAndReadOne(54);
                        Date sysEndTime = DateUtil.getChooseDate(businessAccount.getOrderTime(), 2, Integer.valueOf(sysValue));
                        if (project.getFinalTime() == null){
                            //  确认签单的逻辑
                            // 如果结束时间小于当前时间，则把状态改为已掉保
                            if (businessAccount.getEndTime().before(new Date())){
                                businessAccount.setStatus((short) 8);
                            }else {
                            }
                        }else {
                            Date endTime = businessAccount.getEndTime();
                            // 执行完成后的逻辑
                            if (endTime.before(new Date()) || sysEndTime.before(new Date())){
                                // 执行完成受保整个时段内没有进行跟进，状态变更为已掉保
                                businessAccount.setStatus((short) 8);
                            }else {
                                // 在执行完成的受保护月份内，处理逻辑在新增跟进记录里
                            }
                        }
                    }
                    businessAccountMapper.updateByPrimaryKeySelective(businessAccount);
                }else {
                    // 判断确认签单与执行完成后的逻辑
                    BusinessProjectDTO project = businessAccountManageService.getMatchOrderByBusinessAccountId(businessAccount.getId(), null);
                    if (project == null){
                        businessAccount.setStatus((short) 8);
                    }else {
                        String sysValue = sysLabelValueMapper.selectValueBySysIdAndReadOne(35);
                        Date sysEndTime = DateUtil.getChooseDate(businessAccount.getOrderTime(), 2, Integer.valueOf(sysValue));
                        if (project.getFinalTime() == null){
                            //  确认签单的逻辑
                            // 如果结束时间小于当前时间，则把状态改为已掉保
                            if (businessAccount.getEndTime().before(new Date())){
                                businessAccount.setStatus((short) 8);
                            }else {
                            }
                        }else {
                            Date endTime = businessAccount.getEndTime();
                            // 执行完成后的逻辑
                            if (endTime.before(new Date()) || sysEndTime.before(new Date())){
                                // 执行完成受保整个时段内没有进行跟进，状态变更为已掉保
                                businessAccount.setStatus((short) 8);
                            }else {
                                // 在执行完成的受保护月份内，处理逻辑在新增跟进记录里
                            }
                        }
                    }
                    businessAccountMapper.updateByPrimaryKeySelective(businessAccount);
                }
            }
        }
    }


    public void doUpdateBusinessAccount() {
        // 判断商务客户的客保机制
        List<MjBusinessAccount> mjBusinessAccounts = businessAccountMapper.selectTaskList();
        for (MjBusinessAccount businessAccount : mjBusinessAccounts){
            // 判断已合作的品牌是否过保
            if (businessAccount.getStatus() == 4){
                if (businessAccount.getEndTime() == null){
                    String sysValue = sysLabelValueMapper.selectValueBySysIdAndReadOne(35);
                    Date endTime = DateUtil.getChooseDate(businessAccount.getCreateTime(), 2, Integer.valueOf(sysValue));
                    businessAccount.setEndTime(endTime);
                    businessAccount.setBeginTime(businessAccount.getCreateTime());
                    businessAccountMapper.updateByPrimaryKeySelective(businessAccount);
                }
                if (businessAccount.getEndTime() != null && businessAccount.getEndTime().before(new Date())){
                    businessAccountMapper.updateStatusById(businessAccount.getId(), (short) 8);
                }
            }else if (businessAccount.getStatus() == 3){
                // 如果创建时间超过3个月，则过保
                String sysValue = sysLabelValueMapper.selectValueBySysIdAndReadOne(33);
                Date aTime = DateUtil.getChooseDate(businessAccount.getCreateTime(), 2, Integer.valueOf(sysValue));
                if (aTime.before(new Date())){
                    String sysValue34 = sysLabelValueMapper.selectValueBySysIdAndReadOne(34);
                    Integer i = Integer.valueOf(sysValue34);
                    Date bTime = DateUtil.getChooseDate(aTime, 1, -i);
                    MjBusinessAccountFollow businessAccountFollow = businessAccountFollowMapper.selectHasAddByStartTimeAndEndTime(bTime, aTime, businessAccount.getId());
                    if (businessAccountFollow == null){
                        businessAccount.setStatus((short) 8);
                        businessAccountMapper.updateStatusById(businessAccount.getId(), (short) 8);
                    }else {
                        businessAccount.setBeginTime(aTime);
                        businessAccount.setStatus((short) 4);
                        String sysValue35 = sysLabelValueMapper.selectValueBySysIdAndReadOne(35);
                        businessAccount.setEndTime(DateUtil.getChooseDate(aTime, 2, Integer.valueOf(sysValue35)));
                        businessAccountMapper.updateByPrimaryKeySelective(businessAccount);
                    }
                }else {
                    // 在3个月之内
                    // 如果没有结束时间或者没有开始时间，添加数据
                    if (businessAccount.getBeginTime() == null || businessAccount.getEndTime() == null){
                        String sysValue34 = sysLabelValueMapper.selectValueBySysIdAndReadOne(34);
                        Integer num = Integer.valueOf(sysValue34);
                        Date beginTime = null;
                        Date endTime = null;
                        // 获取3个月的天数，除以15天，获取循环次数，利用循环次数获取对应的开始时间和结束时间
                        List<Date> dateList = DateUtil.getDateListByStartTimeAndEndTime(businessAccount.getCreateTime(), aTime);
                        Integer dayNum = dateList.size();
                        BigDecimal divide = BigDecimal.valueOf(dayNum).divide(BigDecimal.valueOf(num), 0, BigDecimal.ROUND_UP);
                        Boolean hasTime = false;
                        for (int j = 0; j < divide.intValue(); j++){
                            BigDecimal j1 = new BigDecimal(j).multiply(new BigDecimal(num));
                            BigDecimal j2 = new BigDecimal(j+1).multiply(new BigDecimal(num));
                            beginTime = DateUtil.getChooseDate(businessAccount.getCreateTime(), 1, j1.intValue());
                            endTime = DateUtil.getChooseDate(businessAccount.getCreateTime(), 1, j2.intValue());
                            if (beginTime.before(new Date()) && endTime.after(new Date())){
                                businessAccount.setBeginTime(beginTime);
                                businessAccount.setEndTime(endTime);
                                hasTime = true;
                            }
                        }
                        if (hasTime){
                            businessAccount.setStatus((short) 3);
                            businessAccountMapper.updateByPrimaryKeySelective(businessAccount);
                        }
                    }
                    // 判断是否是沟通中的品牌是否过保
                    if (businessAccount.getEndTime() != null && businessAccount.getBeginTime() != null){
                        if (businessAccount.getEndTime().before(new Date())){
                            MjBusinessAccountFollow businessAccountFollow = businessAccountFollowMapper.selectHasAddByStartTimeAndEndTime(businessAccount.getBeginTime(), businessAccount.getEndTime(), businessAccount.getId());
                            if (businessAccountFollow == null){
                                businessAccount.setStatus((short) 8);
                                businessAccountMapper.updateStatusById(businessAccount.getId(), (short) 8);
                            }else {
                                String sysValue34 = sysLabelValueMapper.selectValueBySysIdAndReadOne(34);
                                businessAccount.setBeginTime(businessAccount.getEndTime());
                                businessAccount.setEndTime(DateUtil.getChooseDate(businessAccount.getBeginTime(), 2, Integer.valueOf(sysValue34)));
                                businessAccountMapper.updateByPrimaryKeySelective(businessAccount);
                            }
                        }
                    }
                }
            }
        }
    }

}
